package service

import (
	"crow-samba/app/config"
	"crow-samba/app/pkg"
	"errors"
	"fmt"
	"strings"
)

type SambaConfig struct {
	PartList []ConfigPart
}

func (s *SambaConfig) GetConf() (err error) {
	//获取远程配置文件
	response, err := SendCmd("cat " + config.MyEnvs.SambaConfPath + "|grep -v ^#|grep -v ^$")
	if err != nil {
		return err
	}
	//切割配置文件
	partList := getPart(response)
	//组装配置文件
	s.assemble(partList)
	return nil
}

func getPart(configString string) (partList []string) {
	configList := strings.Split(configString, "\n")
	for _, part := range configList {
		p1 := strings.TrimSpace(part)
		if len(p1) != 0 {
			partList = append(partList, p1)
		}
	}
	return partList
}

func (s *SambaConfig) assemble(partList []string) {
	configP := ConfigPart{
		EntryMap: map[string]string{},
	}
	for _, i := range partList {
		if strings.HasPrefix(i, "[") {
			if len(configP.Name) != 0 {
				s.PartList = append(s.PartList, configP)
				configP = ConfigPart{
					EntryMap: map[string]string{},
				}
			}
			configP.Name = i
		} else {
			s1 := strings.Split(i, "=")
			if len(s1) == 2 {
				k := strings.TrimSpace(s1[0])
				v := strings.TrimSpace(s1[1])
				configP.EntryMap[k] = v
			}
		}
	}
	if configP.Name != "" {
		s.PartList = append(s.PartList, configP)
	}
}

func (s *SambaConfig) WriteConf() (response string, err error) {
	var configS string
	for _, part := range s.PartList {
		if len(configS) != 0 {
			configS = configS + "\n"
		}
		configS = configS + part.Name + "\n"
		for k, v := range part.EntryMap {
			configS = configS + "  " + k + " = " + v + "\n"
		}
	}
	cmdString := "echo " + "\"" + configS + "\" > " + config.MyEnvs.SambaConfPath
	response, err = SendCmd(cmdString)
	if err != nil {
		return response, err
	}
	//systemctl restart smb
	response, err = SendCmd("systemctl restart smb")
	if err != nil {
		return response, err
	}
	fmt.Println(configS)
	return response, nil
}

func (s *SambaConfig) AddPart(part ...ConfigPart) {
	s.PartList = append(s.PartList, part...)
}

func (s *SambaConfig) DeletePart(partName string) (nS *SambaConfig) {
	nS = &SambaConfig{}
	for _, p := range s.PartList {
		if p.Name != partName {
			nS.PartList = append(nS.PartList, p)
		}
	}
	return nS
}

func (s *SambaConfig) GetGlobal() (global ConfigPart, err error) {
	s.GetConf()
	for _, part := range s.PartList {
		if part.Name == "[global]" {
			return part, nil
		}
	}
	return global, errors.New("未找到global模块")
}

func (s *SambaConfig) AddWriter(dirTag string, addUserList []string) {
	for i, p := range s.PartList {
		//找到该目录
		if p.Name == pkg.DirTag2PathName(dirTag) {
			p.AddWriter(addUserList)
			s.PartList[i] = p
		}
	}
}

func (s *SambaConfig) RemoveWriters(partName string, delUserList []string) {
	for i, p := range s.PartList {
		//找到该目录
		if p.Name == partName {
			//调用part删除writer的方法
			p.RemoveWriter(delUserList)
			s.PartList[i] = p
		}
	}
}
